package com.fjnu.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.context.annotation.EnableAspectJAutoProxy;

import javax.sql.DataSource;

/**
 * @desc:
 * @author:
 * @date:
 */

@Configuration
@ComponentScan(basePackages = "com.fjnu")
@PropertySource("classpath:db.properties")
@EnableTransactionManagement  // 启用事务管理
@EnableAspectJAutoProxy  // 启用AspectJ自动代理
@Slf4j
public class SpringConfig {
    @Value("${mysql.driver}")
    private String driver ;
    @Value("${mysql.url}")
    private String url ;
    @Value("${mysql.username}")
    private String username ;
    @Value("${mysql.password}")
    private String password ;
    
    @Bean
    public DataSource dataSource() {
        try {
            com.mysql.cj.jdbc.MysqlDataSource dataSource = new com.mysql.cj.jdbc.MysqlDataSource();
            dataSource.setUrl(url);
            dataSource.setUser(username);
            dataSource.setPassword(password);
            return dataSource;
        } catch (Exception e) {
            log.error("数据库连接失败", e);
        }
        return null;
    }
    
    @Bean
    public PlatformTransactionManager transactionManager(DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }
}